package Aleehot100;

/**
 * ClassName: c097
 * Package: Aleehot100
 * Description:169. 多数元素
 *
 * @Author BCXJ
 * @Create 2025/9/16 07:35
 * @Version 1.0
 * @Since 1.0
 */
public class c097 {
    public static void main(String[] args) {
        int[] arr = {2,2,1,1,1,2,2};
        System.out.println(majorityElement(arr));
    }


    public static int majorityElement(int[] nums) {
        // 候选元素和出现次数 初始化
        int candidate = nums[0];
        int count = 1;

        // 选举
        for (int i = 1; i < nums.length; i++) {
            // 选举票数为0，重新初始化
            if(count == 0) {
                candidate = nums[i];
                count = 1;
            }
            else if(candidate == nums[i]) {
                count ++;
            } else {
                count --;
            }
        }

        return candidate;
    }
}
